package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"user_verification/models"
	"user_verification/pkg"
	"user_verification/userrpc/internal/svc"
	"user_verification/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserAuthLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserAuthLogic {
	return &UserAuthLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserAuthLogic) UserAuth(in *userrpc.UserAuthRequest) (*userrpc.UserAuthResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	data, err := user.FindUserById(in.UserId)
	if err != nil {
		return nil, err
	}
	if data.ID == 0 {
		return nil, errors.New("当前用户不存在")
	}
	if data.IdCard != "" {
		return nil, errors.New("当前用户已经实名过了")
	}
	err = pkg.UserAuth(in.IdCard, in.RealName)
	if err != nil {
		return nil, err
	}
	user = models.User{
		Model:    gorm.Model{ID: data.ID},
		IdCard:   in.IdCard,
		RealName: in.RealName,
	}
	if user.Updates() != nil {
		return nil, errors.New("实名认证失败")
	}
	return &userrpc.UserAuthResponse{
		UserId: int64(user.ID),
	}, nil
}
